package com.banciyuan.bcywebview.biz.follow;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.TimelineLikeHelper;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.imageview.CircleImageView;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.daoexample.model.MineInfo;
import de.greenrobot.daoexample.model.Role;

/**
 * Created by hy on 2015/4/28.
 */
public class FollowAdapter extends BaseAdapter {

    private List<MineInfo> data = new ArrayList<MineInfo>();
    private Context context;
    private ImageLoader imageLoader;
    private boolean removeFansFlag = false;

    public FollowAdapter(Context context, List<MineInfo> data) {
        this.context = context;
        this.data = data;
        imageLoader = ImageLoader.getInstance();
    }

    public void addData(List<MineInfo> moreData) {
        data.addAll(moreData);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int i) {
        return data.get(i);
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertview, ViewGroup viewGroup) {
        final ViewHolder viewHolder;
        if (null == convertview) {
            viewHolder = new ViewHolder();
            convertview = View.inflate(context, R.layout.mylike_item, null);
            viewHolder.civTouXiang = (CircleImageView) convertview.findViewById(R.id.civ_touxiang);
            viewHolder.tvGuanzhuName = (TextView) convertview.findViewById(R.id.tv_guanzhu_name);
            viewHolder.tvCoser = (TextView) convertview.findViewById(R.id.tv_coser);
            viewHolder.tvDrawer = (TextView) convertview.findViewById(R.id.tv_drawer);
            viewHolder.tvWriter = (TextView) convertview.findViewById(R.id.tv_writer);
            viewHolder.ivMarkStatus = (TextView) convertview.findViewById(R.id.iv_status_mark);
            viewHolder.ivUnMarkStatus = (TextView) convertview.findViewById(R.id.iv_status_unmark);
            viewHolder.ivMarkEachOtherStatus = (TextView) convertview.findViewById(R.id.iv_status_mark_eachother);
            viewHolder.viewRemoveFollowers = convertview.findViewById(R.id.iv_status_remove_followers);
            convertview.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertview.getTag();
        }
        MineInfo mineInfo = data.get(position);
        setUserInfo(viewHolder, mineInfo);
        setRoles(viewHolder, mineInfo);
        setFollowState(viewHolder, mineInfo);
        setAction(position, viewHolder, mineInfo);
        return convertview;
    }

    private void setAction(final int position, final ViewHolder viewHolder, final MineInfo mineInfo) {
        viewHolder.ivMarkStatus.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                showFollowDialog(mineInfo, viewHolder, position);
            }
        });
        viewHolder.ivUnMarkStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doFollow(mineInfo, viewHolder, "dofollow", position);
            }
        });
        viewHolder.ivMarkEachOtherStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showFollowDialog(mineInfo, viewHolder, position);
            }
        });
        viewHolder.viewRemoveFollowers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUnFollowDialog(mineInfo);
            }
        });
    }

    private void showUnFollowDialog(final MineInfo mineInfo) {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(context);
        builder.setDescString(context.getString(R.string.comfirm_removefans))
                .setActionString(context.getString(R.string.mydialog_comfirm))
                .setCancelString(context.getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        removeFans(mineInfo);
                    }
                }).create().show();
    }

    private void showFollowDialog(final MineInfo mineInfo, final ViewHolder viewHolder, final int position) {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(context);
        builder.setDescString(context.getString(R.string.comfirm_unfollow_people))
                .setActionString(context.getString(R.string.mydialog_comfirm))
                .setCancelString(context.getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doFollow(mineInfo, viewHolder, "unfollow", position);
                    }
                }).create().show();
    }

    private void setUserInfo(final ViewHolder viewHolder, MineInfo mineInfo) {
        viewHolder.tvGuanzhuName.setText(mineInfo.getUname());
        String avatar = mineInfo.getAvatar();
        viewHolder.civTouXiang.setImageResource(R.drawable.user_pic_big);
        viewHolder.civTouXiang.setTag(avatar);
        if (StringUtil.notNullStartWithUrlHead(avatar)) {
            imageLoader.loadImage(avatar, ImageOptions.optionHead, new SimpleImageLoadingListener() {
                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                    Object tag = viewHolder.civTouXiang.getTag();
                    if (null != tag && tag.equals(imageUri)) {
                        viewHolder.civTouXiang.setImageBitmap(loadedImage);
                    }
                }
            });
        }
    }

    private void setFollowState(ViewHolder viewHolder, MineInfo mineInfo) {
        String follow_state = mineInfo.getFollow_state();
        if (removeFansFlag) {
            viewHolder.ivMarkEachOtherStatus.setVisibility(View.GONE);
            viewHolder.ivUnMarkStatus.setVisibility(View.GONE);
            viewHolder.ivMarkStatus.setVisibility(View.GONE);
            viewHolder.viewRemoveFollowers.setVisibility(View.VISIBLE);
        } else {
            viewHolder.ivMarkEachOtherStatus.setVisibility(View.GONE);
            viewHolder.ivUnMarkStatus.setVisibility(View.GONE);
            viewHolder.ivMarkStatus.setVisibility(View.GONE);
            viewHolder.viewRemoveFollowers.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mineInfo.getUid()) && !mineInfo.getUid().equals(UserDataHelper.getInstance(context).getUid())) {
                if ("havefollow".equals(follow_state)) {
                    viewHolder.ivMarkStatus.setVisibility(View.VISIBLE);
                } else if ("eachfollow".equals(follow_state)) {
                    viewHolder.ivMarkEachOtherStatus.setVisibility(View.VISIBLE);
                } else if ("unfollow".equals(follow_state)) {
                    viewHolder.ivUnMarkStatus.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void setRoles(ViewHolder viewHolder, MineInfo mineInfo) {
        List<Role> roles = mineInfo.getRoles();
        viewHolder.tvCoser.setVisibility(View.GONE);
        viewHolder.tvDrawer.setVisibility(View.GONE);
        viewHolder.tvWriter.setVisibility(View.GONE);
        if (null != roles && !roles.isEmpty()) {
            for (int i = 0; i < roles.size(); i++) {
                String type_name = roles.get(i).getType_name();
                if (context.getString(R.string.coser_role).equals(type_name)) {
                    if (roles.size() < 3) {
                        viewHolder.tvCoser.setText(context.getString(R.string.coser_role));
                    } else {
                        viewHolder.tvCoser.setText(context.getString(R.string.coser_role) + "  /");
                    }
                    viewHolder.tvCoser.setVisibility(View.VISIBLE);
                }
                if (context.getString(R.string.draw_role).equals(type_name)) {
                    if (roles.size() == 1) {
                        viewHolder.tvDrawer.setText(context.getString(R.string.draw_role));
                    } else if (roles.size() > 1) {
                        viewHolder.tvDrawer.setText(context.getString(R.string.draw_role) + "  /");
                    }
                    viewHolder.tvDrawer.setVisibility(View.VISIBLE);
                }
                if (context.getString(R.string.write_role).equals(type_name)) {
                    viewHolder.tvWriter.setText(context.getString(R.string.write_role));
                    viewHolder.tvWriter.setVisibility(View.VISIBLE);
                }

            }
        }
    }

    private void removeFans(final MineInfo mineInfo) {
        TimelineLikeHelper.removeFans(context, mineInfo.getUid(), new TimelineLikeHelper.FollowSuccess() {
            @Override
            public void onFollowSuccess(String response) {
                if ("01".equals(response)) {
                    data.remove(mineInfo);
                    notifyDataSetChanged();
                } else {
                    MyToast.show(context, context.getString(R.string.remove_fans_fail));
                }
            }
        });
    }

    private void doFollow(MineInfo mineInfo, final ViewHolder viewHolder, String type, final int position) {
        final int flag = type.equals("dofollow") ? 0 : 1;
        TimelineLikeHelper.doFollow(context, type, mineInfo.getUid(),
                new TimelineLikeHelper.FollowSuccess() {
                    @Override
                    public void onFollowSuccess(String response) {
                        try {
                            JSONObject result = new JSONObject(response);
                            String content = result.getString(HttpUtils.UPLOAD_DATA);
                            switch (flag) {
                                case 1:
                                    if ("01".equals(content)) {
                                        viewHolder.ivMarkEachOtherStatus.setVisibility(View.GONE);
                                        viewHolder.ivMarkStatus.setVisibility(View.GONE);
                                        viewHolder.ivUnMarkStatus.setVisibility(View.VISIBLE);
                                        data.get(position).setFollow_state("unfollow");
                                    }
                                    break;
                                case 0:
                                    if ("11".equals(content) || "12".equals(content)) {
                                        viewHolder.ivMarkEachOtherStatus.setVisibility(View.GONE);
                                        viewHolder.ivUnMarkStatus.setVisibility(View.GONE);
                                        viewHolder.ivMarkStatus.setVisibility(View.VISIBLE);
                                        data.get(position).setFollow_state("havefollow");
                                    }
                                    if ("13".equals(content)) {
                                        viewHolder.ivMarkStatus.setVisibility(View.GONE);
                                        viewHolder.ivUnMarkStatus.setVisibility(View.GONE);
                                        viewHolder.ivMarkEachOtherStatus.setVisibility(View.VISIBLE);
                                        data.get(position).setFollow_state("eachfollow");
                                    }
                                    break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
        );
    }

    public void setRemoveFlags(boolean removeFansFlag) {
        this.removeFansFlag = removeFansFlag;
        notifyDataSetChanged();
    }

    static class ViewHolder {
        CircleImageView civTouXiang;
        TextView tvGuanzhuName;
        TextView tvCoser;
        TextView tvDrawer;
        TextView tvWriter;
        TextView ivMarkStatus;
        TextView ivUnMarkStatus;
        TextView ivMarkEachOtherStatus;
        View viewRemoveFollowers;
    }

}
